<template>
  <div class="publish-container">
    <el-card class="publish-card">
      <template #header>
        <h2 class="publish-title">发布商品</h2>
      </template>

      <el-form ref="publishFormRef" :model="publishForm" :rules="publishRules" label-width="100px" class="publish-form">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="publishForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="publishForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="publishForm.price" :min="0" :precision="2" placeholder="请输入价格" />
        </el-form-item>

        <!-- <el-form-item label="原价" prop="originalPrice">
          <el-input-number v-model="publishForm.originalPrice" :min="0" :precision="2" placeholder="请输入原价" />
        </el-form-item> -->

        <el-form-item label="库存数量" prop="inventory">
          <el-input-number v-model="publishForm.inventory" :min="1" :precision="0" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="商品成色" prop="oldLevel">
          <el-select v-model="publishForm.oldLevel" placeholder="请选择商品成色">
            <el-option label="全新" :value=100 />
            <el-option label="几乎全新" :value=95 />
            <el-option label="轻微使用痕迹" :value=90 />
            <el-option label="明显使用痕迹" :value=85 />
          </el-select>
        </el-form-item>


        <el-form-item label="商品图片" prop="coverList">
          <el-upload class="avatar-uploader" name="image" action="http://localhost:8080/user/upload"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleAvatarError">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述" prop="detail">
          <el-input v-model="publishForm.detail" type="textarea" :rows="6" placeholder="请详细描述商品信息..." />
        </el-form-item>

        <el-form-item label="可砍价">
          <el-switch v-model="publishForm.isBargain" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handlePublish" :loading="loading">
            发布商品
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogVisible" title="图片预览">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Category } from '@/types'
import { useProductStore } from '@/stores/product'
import request from '@/utils/request'
import type { UploadProps } from 'element-plus'

const router = useRouter()
const productStore = useProductStore()

const publishFormRef = ref()
const loading = ref(false)
const fileList = ref<any[]>([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

const categories = ref<Category[]>([])

const publishForm = reactive({
  name: '',
  categoryId: undefined as number | undefined,
  price: 0,
  //originalPrice: 0,
  inventory: 1,
  oldLevel: 100,
  detail: '',
  isBargain: false,
  coverList: ''
})

const publishRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  inventory: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '商品描述长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
}
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log('头像上传成功:', response)
  imageUrl.value = response.data
  publishForm.coverList = imageUrl.value
  ElMessage.success('头像上传成功')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
// 头像上传失败处理
const handleAvatarError: UploadProps['onError'] = (error, file) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// const handlePictureCardPreview = (file: any) => {
//   dialogImageUrl.value = file.url
//   dialogVisible.value = true
// }

const loadCategories = async () => {
  try {
    // 调用后端分类接口获取分类列表
    const response = await request.get('/category/list', {
      params: {
        pageSize: 20,
      }
    })
    console.log('分类API响应:', response)

    // 检查响应数据结构
    if (response && response.data) {
      // 确保response.data是数组
      const categoryData = Array.isArray(response.data) ? response.data :
        (response.data.data && Array.isArray(response.data.data)) ? response.data.data : []

      if (categoryData.length > 0) {
        categories.value = categoryData.filter((cat: Category) => cat.isUse)
      } else {
        throw new Error('分类数据为空')
      }
    } else {
      throw new Error('分类API响应格式错误')
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API不可用，使用默认分类
    categories.value = [
      { id: 1, name: '电子产品', isUse: true },
      { id: 2, name: '服装配饰', isUse: true },
      { id: 3, name: '家居用品', isUse: true },
      { id: 4, name: '运动户外', isUse: true },
      { id: 5, name: '图书音像', isUse: true }
    ]
  }
}
const user = localStorage.getItem('user')
const userName = user ? JSON.parse(user).username : null

const handlePublish = async () => {
  try {
    await publishFormRef.value.validate()
    loading.value = true


    await productStore.createProduct({
      name: publishForm.name,
      categoryId: publishForm.categoryId!,
      price: publishForm.price,
      //originalPrice: publishForm.originalPrice,
      inventory: publishForm.inventory,
      //description: publishForm.description,
      oldLevel: publishForm.oldLevel,
      detail: publishForm.detail,
      isBargain: publishForm.isBargain ? true : false,
      //images: publishForm.images
      coverList: publishForm.coverList,
      userName: userName,
    })

    ElMessage.success('发布成功！')
    router.push('/user/products')
  } catch (error: any) {
    ElMessage.error(error.message || '发布失败')
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  publishFormRef.value.resetFields()
  publishForm.coverList = ''
  fileList.value = []
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped lang="scss">
.publish-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.publish-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.publish-title {
  text-align: center;
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.publish-form {
  margin-top: 20px;
}

.avatar-uploader {
  text-align: center;

  .avatar {
    width: 100px;
    height: 100px;
    //border-radius: 50%;
    object-fit: cover;
    border: 2px solid #d9d9d9;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: $primary-color;
      transform: scale(1.05);
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 2px dashed #d9d9d9;
    //border-radius: 50%;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: $primary-color;
      color: $primary-color;
    }
  }
}
</style>